import sys

import six

from lib.handler.scheduler import SchedulerObj
from lib.property.application_property import ApplicationProperty
from lib.utils.print_util import PrintUtil


def scheduler_obj(key, value):
    obj = SchedulerObj()
    obj.set_trigger(key)
    val_arr = str(value).split("|")
    props = dict()
    for val in val_arr:
        v_arr = val.split(":")
        key = v_arr[0]
        num = int(v_arr[1])
        props.setdefault(key, num)
    obj.set_prop(props)
    return obj


def scheduler_init(sch_map):
    _sch_map = {}
    for n_key, v_map in six.iteritems(sch_map):
        for key, value in six.iteritems(v_map):
            obj = scheduler_obj(key, value)
            _sch_map.setdefault(n_key, obj)
    return _sch_map


class SchedulerInit(object):
    server_schedule = {}

    @staticmethod
    def start():
        from lib.init.application_init import ApplicationInit
        server_name = ApplicationInit.prop.get(ApplicationProperty.SYSTEM_SCHEDULE_SERVER)
        if not server_name:
            PrintUtil.start("Start scheduler setting is error, no server names ...")
            sys.exit(0)
        PrintUtil.start("Start scheduler setting ...")
        server_name_arr = str(server_name).split(",")
        sch_map = {}
        for name in server_name_arr:
            temp_map = {}
            temp_trigger = name + "." + ApplicationProperty.SCHEDULE_TRIGGER
            temp_prop = name + "." + ApplicationProperty.SCHEDULE_PROP
            trigger_value = ApplicationInit.prop.get(temp_trigger)
            prop_value = ApplicationInit.prop.get(temp_prop)
            temp_map.setdefault(trigger_value, prop_value)
            sch_map.setdefault(name, temp_map)

        # 初始化
        SchedulerInit.server_schedule = scheduler_init(sch_map)
